package com.example.base.websocket.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.base.security.jwt.JWTTokenUtil;
import com.example.base.system.SysAppService;
import com.example.base.system.domain.OpenUserToken;
import com.example.base.system.domain.SysApp;
import com.example.base.system.service.OpenUserTokenService;
import com.example.base.utils.ResponseUtils;
import com.example.base.utils.Result;
import com.example.base.utils.SpringContextUtils;
import com.example.base.websocket.WsAppSessionManager;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class AppWebSocketInterceptor implements HandshakeInterceptor {




    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        try {
            log.info("url  地址:{}",request.getURI().getPath());
            log.info("host 地址:{}",request.getLocalAddress().getHostString());

            List<String> openTokenList=request.getHeaders().get("openToken");
            if(openTokenList!=null &&openTokenList.size() >0){
                String openToken=openTokenList.get(0);
                OpenUserTokenService tokenService=SpringContextUtils.getBean(OpenUserTokenService.class);
                OpenUserToken userToken=tokenService.valited(openToken);
                if(userToken!=null){
                    return true;
                }
            }
            List<String> stringList=request.getHeaders().get("token");
            if(stringList!=null && stringList.size()>0){
                String token=stringList.get(0);
                Claims claims=JWTTokenUtil.getClaimsByToken(token);
                if(claims==null){
                    return false;
                }
            }else {
                return false;
            }
            String appName= WsAppSessionManager.getAppName(request.getURI().getPath());
            SysAppService sysAppService=SpringContextUtils.getBean(SysAppService.class);
            SysApp sysApp=sysAppService.getSysAppByAppName(appName);
            if(sysApp==null){
                return false;
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
